using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using GotLyrics;
using System.IO;
using System.Net;

namespace GotLyrics_Console
{
    class ProgramOld
    {
        private static string _filename;
        private static bool _isDirectory;
        private static bool _skip;
        private static bool _force;
        private static bool _display;
        private static bool _recursive;
        private static bool _test;
        private static bool _save;

        private static ILyricGrabber[] _lyricGrabbers;

        static void _Main(string[] args)
        {
            Assembly asm = Assembly.GetExecutingAssembly();
            string asmName = asm.GetName().Name;
            string version = Common.GetAssemblyFileVersion(asm);
            Console.WriteLine("{0} v{1}", asmName, version);

            if (ParseArguments(args))
            {
                if (_isDirectory)
                    ScanDirectory(_filename);
                else
                    GetLyrics(_filename);
            }
        }

        private static void ScanDirectory(string directory)
        {
            Console.WriteLine("Scanning directory \"" + directory + "\" ...");

            string[] files = Directory.GetFiles(directory, "*.mp3");

            foreach (string file in files)
                GetLyrics(file);

            if (_recursive)
            {
                string[] folders = Directory.GetDirectories(directory);

                foreach (string folder in folders)
                    ScanDirectory(folder);
            }
        }

        private static void GetLyrics(string file)
        {
            Console.WriteLine("Processing \"" + file + "\" ...");

            LyricGrabberContext context = new LyricGrabberContext(file);

            if (!string.IsNullOrEmpty(context.Tags.UnsyncedLyrics))
            {
                Console.WriteLine("File already contains lyrics.");

                if (_skip)
                    return;

                if (!_force)
                {
                    Console.Write("Overwrite? ");

                    ConsoleKeyInfo k = Console.ReadKey();

                    Console.Write("\n");

                    if (k.KeyChar != 'y')
                    {
                        Console.WriteLine("Skipping.");
                        return;
                    }
                }
            }

            string lyrics = null;
            string textfilename = null; 

            foreach (ILyricGrabber grabber in _lyricGrabbers)
            {
                if (grabber.Enabled == false)
                    continue;

                Console.WriteLine("Checking for lyrics on " + grabber.WebSiteUrl);

                try
                {
                    lyrics = grabber.Execute(context);
                }
                catch (WebException ex)
                {
                    Console.WriteLine("The following web exception has occured:\n" + ex.ToString());
                    Console.WriteLine("\nDisabling current grabber.");

                    grabber.Enabled = false;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error occured while grabbing lyric:\n" + ex.ToString());
                    continue;
                }

                if (!string.IsNullOrEmpty(lyrics))
                {
                    textfilename = string.Format("{0}.{1}.txt", Path.GetFileNameWithoutExtension(file), grabber.GetType().Name);
                    textfilename = Path.Combine(Path.GetDirectoryName(file), textfilename);

                    if (_test)
                    {
                        Console.WriteLine("Found lyrics.");

                        if (_display)
                        {
                            Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
                            Console.WriteLine(lyrics);
                            Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
                        }

                        if (_save)
                        {
                            using (StreamWriter sw = File.CreateText(textfilename))
                            {
                                sw.Write(lyrics);
                            }
                        }

                        continue;
                    }

                    break;
                }
            }

            if (!string.IsNullOrEmpty(lyrics) && !_test)
            {
                Console.WriteLine("Found lyrics.");

                if (_display)
                {
                    Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
                    Console.WriteLine(lyrics);
                    Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
                }

                if (_save)
                {
                    using (StreamWriter sw = File.CreateText(textfilename))
                    {
                        sw.Write(lyrics);
                    }
                }

                context.Tags.UnsyncedLyrics = lyrics;

                if (!_test)
                {
                    Console.WriteLine("Saving file.");
                    context.Write();
                }
            }
            else
                Console.WriteLine("No lyrics found!");
        }

        private static bool ParseArguments(string[] args)
        {
            foreach (string arg in args)
            {
                if (arg[0] == '/')
                {
                    switch (arg[1])
                    {
                        case 'h':
                            DisplayUsage();
                            return false;

                        case 's':
                            _skip = true;
                            break;

                        case 'S':
                            _save = true;
                            break;

                        case 'f':
                            _force = true;
                            break;

                        case 'd':
                            _display = true;
                            break;

                        case 'r':
                            _recursive = true;
                            break;

                        case 't':
                            _test = true;
                            break;

                        default:
                            Console.WriteLine("Unknown argument: " + arg);
                            return false;
                    }
                }
                else
                {
                    // Assume filename
                    _filename = arg.Trim("\" \\/".ToCharArray());
                }
            }

            if (string.IsNullOrEmpty(_filename))
            {
                Console.WriteLine("No input file given.\n");
                DisplayUsage();
                return false;
            }

            _isDirectory = Directory.Exists(_filename);

            if (_isDirectory)
                Console.WriteLine("\"" + _filename + "\" is a directory.");

            Console.WriteLine("Looking for LyricGrabbers ...");

            _lyricGrabbers = Common.GetLyricGrabbers();

            if (_lyricGrabbers == null || _lyricGrabbers.Length == 0)
            {
                Console.WriteLine("No LyricGrabbers found.");
                return false;
            }

            foreach (ILyricGrabber grabber in _lyricGrabbers)
            {
                Console.WriteLine(grabber.GetType().Name + " (" + grabber.WebSiteUrl + ")");
            }

            return true;
        }

        private static void DisplayUsage()
        {
            Assembly asm = Assembly.GetExecutingAssembly();

            string asmName = asm.GetName().Name;
            Console.WriteLine("Usage: {0} (filename|directory) [options]", asmName);
            Console.WriteLine("/help        Help!");
            Console.WriteLine("/skip        Skip files which already have lyrics.");
            Console.WriteLine("/force       No prompt for overwriting existing lyrics.");
            Console.WriteLine("/display     Display the found lyric.");
            Console.WriteLine("/recursive   Updates all files beneath the given directory.");
            Console.WriteLine("/test        Turn on testing. Will not save the lyrics and will continue");
            Console.WriteLine("             executing grabber plugins even when a lyric has been found.");
            Console.WriteLine("/Save        Save the found lyrics in text files.");
        }
    }
}
